package com.tvein.web.controller.FileLoader
{
	//flash
	import flash.net.LocalConnection;
	import flash.utils.ByteArray;
	//pureMVC
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;
	//custom
	import com.tvein.web.common.CommonConstants;
	import com.tvein.web.model.FilesProxy;
//
	public class FileGet extends SimpleCommand implements ICommand
	{
		private var filesData:FilesProxy;
		
		override public function execute(notification:INotification) : void
		{
			filesData = facade.retrieveProxy(FilesProxy.NAME) as FilesProxy;
			filesData.cacheAdd([notification.getBody()[0], notification.getBody()[1], notification.getBody()[2]]);
			
			var localConnection:LocalConnection = new LocalConnection();
			var chunks:Array = new Array();
			
			for (var i:int = 0; i < filesData.cachesArray.length; i++)
			{
				if (notification.getBody()[0] == filesData.cachesArray[i][0])
				{
					chunks[filesData.cachesArray[i][1]] = filesData.cachesArray[i][2];
				}
			}
			
			if (chunks[0] is int)
			{
				var finished:Boolean = true;
				var fileData:ByteArray = new ByteArray();
				
				for (var j:int = 1; j < chunks[0]; j++)
				{
					if (chunks[j] == undefined)
					{
						finished = false;
						
						localConnection.send(CommonConstants.SYSTEM_CHANNEL, "console", ["/fileloader -N", [CommonConstants.WEB_CHANNEL, notification.getBody()[0], j]]);
						
					}
					else
					{
						fileData.writeBytes(chunks[j]);
					}
				}
				
				if (finished == true)
				{ 
					for (var k:int = 0; k < filesData.cachesArray.length; k++)
					{
						filesData.cachesArray.splice(k, 1);
						k --;
					}
					
					filesData.filesDataAdd([notification.getBody()[0], fileData]);
					sendNotification(CommonConstants.FILELOADER, ["/fileloader -L", notification.getBody()[0]]);
				}
				
				fileData = null;
				chunks = null;
			}
			
			localConnection = null;
		}
	}
}